<template>
	<view class="technician-apply">
		<!-- 导航栏 -->
		<nav-bar backUrl="/pages/collaboration/collaboration" :isTabbar="true"></nav-bar>
		<!-- 添加申请记录按钮 -->
		<view class="record-btn" @tap="goToRecord">
			<text class="record-text">申请记录</text>
		</view>
		<view class="form-container">
			<!-- 表单输入项 -->
			<view class="form-item">
				<input type="text" v-model="formData.name" placeholder="姓名" class="input"
					:class="{'highlighted': isNameHighlighted}" />
			</view>
			<view class="form-item">
				<input type="number" v-model="formData.phone" placeholder="手机号" class="input" />
			</view>
			<view class="form-item">
				<input type="text" v-model="formData.idCard" placeholder="身份证号" class="input"
					:class="{'highlighted': isIdCardHighlighted}" />
			</view>
			<!-- 门店选择 -->
			<view class="form-item">
				<view class="store-selector" @tap="showStoreSelector">
					<text class="selector-text">{{ formData.storeName || '请选择门店' }}</text>
					<text class="selector-icon">▼</text>
				</view>
			</view>
			<!-- 身份证照片上传 -->
			<view class="upload-section">
				<view class="upload-title">上传身份证照片</view>
				<view class="upload-container">
					<!-- 正面照片 -->
					<view class="upload-item" @tap="chooseImage('front')">
						<image v-if="formData.idCardFront" :src="formData.idCardFront" mode="aspectFill"
							class="preview-image"></image>
						<view v-else class="upload-placeholder">
							<text class="iconfont icon-add">+</text>
							<text class="upload-text">身份证正面</text>
						</view>
						<view class="loading-overlay" v-if="frontLoading">
							<view class="loading-spinner"></view>
							<text class="loading-text">识别中...</text>
						</view>
					</view>
					<!-- 反面照片 -->
					<view class="upload-item" @tap="chooseImage('back')">
						<image v-if="formData.idCardBack" :src="formData.idCardBack" mode="aspectFill"
							class="preview-image"></image>
						<view v-else class="upload-placeholder">
							<text class="iconfont icon-add">+</text>
							<text class="upload-text">身份证反面</text>
						</view>
						<view class="loading-overlay" v-if="backLoading">
							<view class="loading-spinner"></view>
							<text class="loading-text">识别中...</text>
						</view>
					</view>
				</view>
			</view>
			<!-- 提交按钮 -->
			<view class="submit-btn" @tap="submitForm">提交申请</view>
		</view>
		<!-- 门店选择器弹窗 -->
		<view class="store-popup" v-if="showStorePopup">
			<view class="popup-mask" @tap="hideStoreSelector"></view>
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">选择门店</text>
					<text class="popup-close" @tap="hideStoreSelector">×</text>
				</view>
				<view class="popup-search">
					<input type="text" v-model="storeSearchKeyword" placeholder="搜索门店" class="search-input" />
				</view>
				<scroll-view class="store-list" scroll-y>
					<view class="store-item" v-for="(store, index) in filteredStores" :key="index"
						@tap="selectStore(store)" :class="{'active': formData.storeId === store.id}">
						<view class="store-info">
							<text class="store-name">{{ store.storeName }}</text>
							<text class="store-address">{{ store.address }}</text>
						</view>
						<text class="select-icon" v-if="formData.storeId === store.id">✓</text>
					</view>
					<view class="empty-tip" v-if="filteredStores.length === 0">
						<text>未找到相关门店</text>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>
<script>
	import NavBar from '@/components/nav-bar/nav-bar.vue'

	export default {
		components: {
			NavBar
		},
		data() {
			return {
				jWeixin: null,
				formData: {
					name: '',
					phone: '',
					idCard: '',
					idCardFront: '',
					idCardBack: '',
					idCardFrontUrl: '',
					idCardBackUrl: '',
					storeId: '',
					storeName: ''
				},
				wxReady: false,
				isWechatEnv: false,
				frontLoading: false,
				backLoading: false,
				isNameHighlighted: false,
				isIdCardHighlighted: false,
				// 门店选择相关
				showStorePopup: false,
				storeSearchKeyword: '',
				storeList: [],
				isIOS: false
			}
		},
		computed: {
			// 过滤后的门店列表
			filteredStores() {
				if (!this.storeSearchKeyword) {
					return this.storeList;
				}
				const keyword = this.storeSearchKeyword.toLowerCase();
				return this.storeList.filter(store =>
					store.storeName.toLowerCase().includes(keyword) ||
					(store.address && store.address.toLowerCase().includes(keyword))
				);
			}
		},
		onLoad() {
			// iOS 首次进入自动刷新
			// this.isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
			// if (this.isIOS && !sessionStorage.getItem('iosRefreshed_technicianApply')) {
			// 	sessionStorage.setItem('iosRefreshed_technicianApply', 'true');
			// 	window.location.reload();
			// 	return;
			// }
			const sys = uni.getSystemInfoSync()
			// 检测是否微信环境
			// this.isWechatEnv = /MicroMessenger/i.test(navigator.userAgent);
			// if (this.isWechatEnv) {
			// 	this.initJssdkConfig();
			// }
			// 加载门店列表
			this.loadStoreList();
		},
		methods: {
			// 加载门店列表
			loadStoreList() {
				uni.showLoading({
					title: '加载门店...'
				});
				uni.request({
					url: `${uni.$config.baseUrl}/store/store/listALL`,
					method: 'GET',
					success: (res) => {
						uni.hideLoading();
						if (res.data && res.data.code === 200) {
							this.storeList = res.data.rows || [];
						} else {
							uni.showToast({
								title: '门店列表加载失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: '门店列表加载失败',
							icon: 'none'
						});
					}
				});
			},
			// 显示门店选择器
			showStoreSelector() {
				this.showStorePopup = true;
			},
			// 隐藏门店选择器
			hideStoreSelector() {
				this.showStorePopup = false;
				this.storeSearchKeyword = '';
			},
			// 选择门店
			selectStore(store) {
				this.formData.storeId = store.id;
				this.formData.storeName = store.storeName;
				this.hideStoreSelector();
			},
			// 初始化JSSDK配置
			initJssdkConfig() {
				// 获取当前页面URL（去除hash部分）
				const url = window.location.href.split('#')[0];
				// 请求后端获取签名配置
				uni.request({
					url: `${uni.$config.baseUrl}/wx/jssdk/config`,
					method: 'GET',
					data: {
						url: url
					},
					success: (res) => {
						if (res.data && res.data.code === 200) {
							console.info(1111,res.data.data)
							this.configWeixin(res.data.data);
						} else {
							uni.showToast({
								title: res.data?.msg || '获取配置失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '获取微信配置失败',
							icon: 'none'
						});
					}
				});
			},
			// 配置微信JSSDK
			configWeixin(config) {
				this.jWeixin = require('jweixin-module')
				this.jWeixin.config({
					debug: true,
					signature: config.signature,
					nonceStr: config.nonceStr,
					timestamp: config.timestamp,
					appId: config.appId,
					jsApiList: [
						'chooseImage',
						'previewImage',
						'uploadImage',
						'downloadImage',
						'getLocalImgData'
					]
				});
				this.jWeixin.ready(() => {
					this.wxReady = true;
				});
				this.jWeixin.error((res) => {
					uni.showToast({
						title: res.errMsg,
						icon: 'none'
					});
				});
			},
			// 选择图片
			chooseImage(type) {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0];
						// 先显示图片
						if (type === 'front') {
							this.formData.idCardFront = tempFilePath;
							this.frontLoading = true;
						} else {
							this.formData.idCardBack = tempFilePath;
							this.backLoading = true;
						}
						// 直接上传文件
						uni.uploadFile({
							url: `${uni.$config.baseUrl}/common/ocr/idCard/upload`,
							filePath: tempFilePath,
							name: 'file',
							formData: {
								cardSide: type
							},
							success: (uploadRes) => {
								// 清除loading状态
								if (type === 'front') {
									this.frontLoading = false;
								} else {
									this.backLoading = false;
								}
								let result;
								try {
									result = JSON.parse(uploadRes.data);
								} catch (e) {
									uni.showToast({
										title: '识别失败，服务器响应无效',
										icon: 'none'
									});
									return;
								}
								if (result && result.code === 200) {
									// 识别成功，更新表单数据
									if (type === 'front') {
										const data = result.data;
										// 高亮显示自动填充的字段
										this.highlightAutofillFields();
										// 更新表单数据
										this.formData.name = data.name || this.formData.name;
										this.formData.idCard = data.id || this.formData
											.idCard;
									}
									// 保存OCR识别后返回的图片URL
									if (type === 'front') {
										this.formData.idCardFrontUrl = result.data.imageUrl;
									} else {
										this.formData.idCardBackUrl = result.data.imageUrl;
									}
									uni.showToast({
										title: '识别成功',
										icon: 'success'
									});
								} else {
									// 非200 情况，优先尝试使用后端返回的 imageUrl
									if (result && result.data && result.data.imageUrl) {
										if (type === 'front') {
											this.formData.idCardFrontUrl = result.data.imageUrl;
										} else {
											this.formData.idCardBackUrl = result.data.imageUrl;
										}
									} else {
										// 如果没有返回 URL，则回退到本地路径，提示用户手动输入
										this.handleOcrQuotaError(type, tempFilePath);
									}
									uni.showToast({
										title: result?.msg || '识别失败',
										icon: 'none'
									});
									console.error('OCR识别返回错误:', result);
								}
							},
							fail: (err) => {
								// 清除loading状态
								if (type === 'front') {
									this.frontLoading = false;
								} else {
									this.backLoading = false;
								}
								uni.showToast({
									title: '识别失败，请重试',
									icon: 'none'
								});
							}
						});
					},
					fail: (err) => {
						console.error('选择图片失败:', err);
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
			},
			// 高亮显示自动填充的字段
			highlightAutofillFields() {
				// 设置高亮状态
				this.isNameHighlighted = true;
				this.isIdCardHighlighted = true;
				// 3秒后恢复正常状态
				setTimeout(() => {
					this.isNameHighlighted = false;
					this.isIdCardHighlighted = false;
				}, 3000);
			},
			// 处理OCR配额不足的情况
			handleOcrQuotaError(cardSide, filePath) {
				// 保存图片，但不进行OCR识别
				if (cardSide === 'front') {
					// 将本地图片路径保存下来，用于后续提交
					this.formData.idCardFrontUrl = filePath;
					// 提示用户手动输入
					uni.showModal({
						title: '提示',
						content: '自动识别服务暂时不可用，请手动输入身份证信息',
						showCancel: false,
						success: () => {
							// 聚焦到姓名输入框
							this.focusNameInput();
						}
					});
				} else {
					// 反面图片，保存路径
					this.formData.idCardBackUrl = filePath;
					uni.showToast({
						title: '图片已保存',
						icon: 'success'
					});
				}
			},
			// 聚焦到姓名输入框
			focusNameInput() {
				// 在Vue中无法直接操作DOM，可以添加标记让输入框自动获取焦点
				this.$nextTick(() => {
					const nameInput = document.querySelector('input[placeholder="姓名"]');
					if (nameInput) {
						nameInput.focus();
					}
				});
			},
			// 提交表单
			submitForm() {
				// 表单验证
				if (!this.validateName(this.formData.name)) {
					uni.showToast({
						title: '姓名格式不正确',
						icon: 'none'
					})
					return
				}
				if (!this.validatePhone(this.formData.phone)) {
					uni.showToast({
						title: '手机号格式不正确',
						icon: 'none'
					})
					return
				}
				if (!this.validateIdCard(this.formData.idCard)) {
					uni.showToast({
						title: '身份证号格式不正确',
						icon: 'none'
					})
					return
				}
				if (!this.formData.storeId) {
					uni.showToast({
						title: '请选择门店',
						icon: 'none'
					})
					return
				}
				if (!this.formData.idCardFront || !this.formData.idCardBack) {
					uni.showToast({
						title: '请上传身份证照片',
						icon: 'none'
					})
					return
				}
				// 调用后端API提交表单数据
				uni.showLoading({
					title: '提交中...'
				})
				// 使用普通表单提交（远程URL）
				this.submitWithJson();
			},
			// 检查是否是本地文件路径
			isLocalFilePath(path) {
				if (!path) return false;
				return typeof path === 'string' && (path.startsWith('/') || path.startsWith('_www/') || path.startsWith(
					'file://'));
			},
			// 使用JSON提交（图片为远程URL）
			submitWithJson() {
				// 获取用户信息
				const userInfoStr = uni.getStorageSync('userInfo')
				let userInfo = null
				if (userInfoStr) {
					try {
						if (typeof userInfoStr === 'string') {
							const parsed = JSON.parse(userInfoStr)
							if (parsed.code === 200 && parsed.data) {
								userInfo = parsed.data
							} else {
								userInfo = parsed
							}
						} else {
							userInfo = userInfoStr
						}
					} catch (e) {
						userInfo = userInfoStr
					}
				}
				// 构建提交数据
				const submitData = {
					memberId: userInfo.memberId,
					name: this.formData.name,
					phoneNumber: this.formData.phone,
					idCardNumber: (this.formData.idCard || '').replace(/\s+/g, '').trim(),
					storeId: this.formData.storeId,
					storeName: this.formData.storeName,
					idCardFrontImage: this.formData.idCardFrontUrl || '', // 使用OCR上传后返回的图片URL
					idCardBackImage: this.formData.idCardBackUrl || '' // 使用OCR上传后返回的图片URL
				};
				// 发送到后端
				uni.request({
					url: `${uni.$config.baseUrl}/technicianApplication/technicianApplication`,
					method: 'POST',
					data: submitData,
					header: {
						'Content-Type': 'application/json'
					},
					success: (res) => {
						uni.hideLoading();
						if (res.data && res.data.code === 200) {
							this.handleSubmitSuccess();
						} else {
							uni.showToast({
								title: res.data?.msg || '提交失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('提交失败:', err);
						uni.showToast({
							title: '提交失败，请重试',
							icon: 'none'
						});
					}
				});
			},
			// 处理提交成功
			handleSubmitSuccess() {
				uni.showToast({
					title: '提交成功',
					icon: 'success'
				});
				// 提交成功后跳转到申请记录页面
				setTimeout(() => {
					uni.navigateTo({
						url: `/pages/technician-apply-record/technician-apply-record`
					});
				}, 1500);
			},
			// 跳转到申请记录页面
			goToRecord() {
				uni.navigateTo({
					url: '/pages/technician-apply-record/technician-apply-record'
				});
			},
			// ------------------ 表单校验 ------------------
			// 校验姓名（2-15 个纯中文字符，不含数字/字母/符号）
			validateName(name) {
				const pattern = /^[\u4e00-\u9fa5]{2,15}$/;
				return pattern.test((name || '').trim());
			},
			// 校验手机号（国内 11 位 1[3-9] 开头）
			validatePhone(phone) {
				const pattern = /^1[3-9]\d{9}$/;
				return pattern.test((phone || '').trim());
			},
			// 简易校验身份证号（15 或 18 位，18 位最后可为 X/x）
			validateIdCard(id) {
				const pattern = /^(\d{15}|\d{17}[\dXx])$/;
				return pattern.test((id || '').trim());
			},
		}
	}
</script>

<style lang="scss">
	.technician-apply {
		min-height: 100vh;
		background-color: #f8f8f8;
		padding: 30rpx;
		position: relative;
		/* 添加相对定位 */

		/* 添加申请记录按钮样式 */
		.record-btn {
			position: absolute;
			top: 30rpx;
			right: 30rpx;
			background-color: #2B87FF;
			color: #fff;
			padding: 10rpx 20rpx;
			border-radius: 30rpx;
			font-size: 28rpx;
			z-index: 10;
			box-shadow: 0 2rpx 10rpx rgba(43, 135, 255, 0.3);

			&:active {
				opacity: 0.8;
			}
		}

		.form-container {
			background-color: #fff;
			border-radius: 12rpx;
			padding: 30rpx;

			.form-item {
				margin-bottom: 30rpx;

				.input {
					width: 100%;
					height: 88rpx;
					background-color: #f8f8f8;
					border-radius: 8rpx;
					padding: 0 30rpx;
					font-size: 28rpx;
					transition: all 0.3s ease;

					&.highlighted {
						background-color: #e6f3ff;
						border: 1px solid #2B87FF;
						animation: highlight-pulse 1.5s ease-in-out;
					}
				}

				.store-selector {
					width: 100%;
					height: 88rpx;
					background-color: #f8f8f8;
					border-radius: 8rpx;
					padding: 0 30rpx;
					font-size: 28rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;

					.selector-text {
						color: #333;

						&:empty:before {
							content: '请选择门店';
							color: #999;
						}
					}

					.selector-icon {
						color: #999;
						font-size: 24rpx;
					}

					&:active {
						background-color: #efefef;
					}
				}
			}

			.upload-section {
				margin-top: 40rpx;

				.upload-title {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 20rpx;
				}

				.upload-container {
					display: flex;
					gap: 20rpx;

					.upload-item {
						flex: 1;
						height: 320rpx;
						background-color: #f8f8f8;
						border-radius: 8rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						overflow: hidden;
						position: relative;

						.preview-image {
							width: 100%;
							height: 100%;
						}

						.upload-placeholder {
							width: 100%;
							height: 100%;
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: center;
							color: #999;
							font-size: 60rpx;

							.upload-text {
								font-size: 28rpx;
								margin-top: 10rpx;
							}
						}

						.loading-overlay {
							position: absolute;
							top: 0;
							left: 0;
							width: 100%;
							height: 100%;
							background-color: rgba(0, 0, 0, 0.6);
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: center;
							z-index: 10;

							.loading-spinner {
								width: 60rpx;
								height: 60rpx;
								border: 4rpx solid rgba(255, 255, 255, 0.3);
								border-radius: 50%;
								border-top-color: #fff;
								animation: spin 1s linear infinite;
								margin-bottom: 20rpx;
							}

							.loading-text {
								color: #fff;
								font-size: 28rpx;
							}
						}
					}
				}
			}

			.submit-btn {
				margin-top: 60rpx;
				height: 88rpx;
				line-height: 88rpx;
				text-align: center;
				background-color: #2B87FF;
				color: #fff;
				font-size: 32rpx;
				border-radius: 44rpx;

				&:active {
					opacity: 0.8;
				}
			}
		}

		// 门店选择器弹窗
		.store-popup {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 999;

			.popup-mask {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background-color: rgba(0, 0, 0, 0.5);
			}

			.popup-content {
				position: absolute;
				bottom: 0;
				left: 0;
				right: 0;
				background-color: #fff;
				border-radius: 24rpx 24rpx 0 0;
				padding-bottom: 40rpx;
				max-height: 80vh;
				display: flex;
				flex-direction: column;

				.popup-header {
					padding: 30rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					border-bottom: 1rpx solid #eee;

					.popup-title {
						font-size: 32rpx;
						font-weight: 500;
						color: #333;
					}

					.popup-close {
						font-size: 40rpx;
						color: #999;
						padding: 10rpx;
					}
				}

				.popup-search {
					padding: 20rpx 30rpx;

					.search-input {
						background-color: #f5f5f5;
						height: 70rpx;
						border-radius: 35rpx;
						padding: 0 30rpx;
						font-size: 28rpx;
					}
				}

				.store-list {
					flex: 1;
					overflow-y: auto;
					max-height: 60vh;

					.store-item {
						padding: 30rpx;
						border-bottom: 1rpx solid #f5f5f5;
						display: flex;
						justify-content: space-between;
						align-items: center;

						&.active {
							background-color: #f0f8ff;
						}

						.store-info {
							flex: 1;

							.store-name {
								font-size: 30rpx;
								color: #333;
								margin-bottom: 10rpx;
								display: block;
							}

							.store-address {
								font-size: 24rpx;
								color: #999;
								display: block;
							}
						}

						.select-icon {
							color: #2B87FF;
							font-size: 40rpx;
							margin-left: 20rpx;
						}
					}

					.empty-tip {
						padding: 40rpx 0;
						text-align: center;
						color: #999;
						font-size: 28rpx;
					}
				}
			}
		}
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}

	@keyframes highlight-pulse {
		0% {
			box-shadow: 0 0 0 0 rgba(43, 135, 255, 0.4);
		}

		70% {
			box-shadow: 0 0 0 10px rgba(43, 135, 255, 0);
		}

		100% {
			box-shadow: 0 0 0 0 rgba(43, 135, 255, 0);
		}
	}
</style>